package xyz.xtgl.config.helper;

import common.core.util.CommonUtil;
import common.core.util.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 *  @Description 无效Token返回处理器
 * @author liubo
 * @created 2019-12-26 14:17
 */
public class CustomTokenExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Throwable cause = authException.getCause();
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            OutputStream outputStream = response.getOutputStream();
            byte[] dataByteArr = CommonUtil.convertObjectToJson(Result.notAuthority("token 无效")).getBytes("UTF-8");
            outputStream.write(dataByteArr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}